'use strict';

var app = angular.module('app');
app.controller('memberUpdateController', ['$scope','$rootScope','$state','$timeout','toaster','$modal',
		function($scope, $rootScope, $state, $timeout, toaster, $modal) {
			$scope.cardStatus = '读身份证(仅IE可用)';
			$scope.projectId = localStorage.getItem('projectId');//根据项目id做一些页面字段的显示与隐藏，如果是projectId==2，就是学校项目，==1是其他
			console.log($scope.projectId);
			$scope.record = {
				personType:'0',
				personState:'0',
				sex:'1',
				contraceptionState:'5',
				marriageState:'10',
				isWriteOff:'2',
				userStatus:'1',
				id:$state.params.id
			};
			
			if ($state.includes('*.member.update')) {
				$scope.loading = true;
				$scope.title = "修改人员";
				$scope.reset = false;//修改不允许重置
				activate($scope.record.id);
				
			} else if ($state.includes('*.member.create')) {
				$scope.title = "新增人员";
				$scope.reset = true;//新增时可以重置
				
			}
			
			//重置表单
			$scope.resetFrom = function(){
			   $scope.record = {
					personType:'0',
					personState:'0',
					sex:'1',
					contraceptionState:'5',
					marriageState:'10',
					isWriteOff:'2',
					userStatus:'1',
					id:$state.params.id
				};
			}

			validate();
			$scope.selUser = function() {
				$scope.record.personId = $scope.record.person.split('_')[0];
				$scope.record.cardNo = $scope.record.person.split('_')[1];
			}
			
            $('.essential-information').css({'z-index':'9'});
            
            $scope.changeTable = function (number) {
                if(number=='1'){
                    $('.essential-information').css({'height':'auto'});
                    $('.details-Infomation').css({'height':'0'});
                    $('.person-infomation').css({'height':'0'});
                }
                if(number=='2'){
                    $('.essential-information').css({'height':'0'});
                    $('.details-Infomation').css({'height':'auto'});
                    $('.person-infomation').css({'height':'0'});
                }
                if(number=='3'){
                    $('.essential-information').css({'height':'0'});
                    $('.details-Infomation').css({'height':'0'});
                    $('.person-infomation').css({'height':'auto'});
                }
			}

            $scope.submit = function() {
				$scope.record.id = $scope.record.personId;
				var m = $scope.record;
				$scope.record.birthday = $("#birthday").val();
				if($scope.record.id != null){//id非空代表着是修改
					if (m) {
						$scope.record.status = '0';
						$scope.isDisabled = true;// 提交disabled
						$.ajax({
							type : 'POST',
							dataType : 'json',
							contentType : 'application/json;charset=UTF-8',
							url : 'dac/userManager/saveOrUpdate',
							data : angular.toJson($scope.record)
						}).then(function(result){
							$scope.loadding = false;
							if (result.httpCode == 200) {// 成功
								toaster.clear('*');
								toaster.pop('success', '', "保存成功");
								$timeout(function() {
									$state.go('main.member.list');
								}, 2000);
							}else if(result.httpCode == 666){
		                        result.msg = '手机号码已经被使用';
							} else {
								toaster.clear('*');
								toaster.pop('error', '', result.msg+"且身份证号码和手机号必须一致");
								$scope.isDisabled = false;
							}
						});
					}
				}else{
					if (m) {
						$scope.record.status = '0';
						$scope.isDisabled = true;// 提交disabled
						$.ajax({
							type : 'POST',
							dataType : 'json',
							contentType : 'application/json;charset=UTF-8',
							url : 'dac/userManager/save',
							data : angular.toJson($scope.record)
						}).then(function(result){
							if(result.httpCode == 200) {// 成功
								toaster.clear('*');
								toaster.pop('success', '', "保存成功");
								$timeout(function() {
									$state.go('main.member.list');
								}, 2000);
							}else if(result.httpCode == 666){
	                       	 result.msg = '手机号码已经被使用';
							} else {
								toaster.clear('*');
								toaster.pop('error', '', result.msg+"且身份证号码和手机号必须一致");
								$scope.isDisabled = false;
							}
						});
					}
					
				}
			}

			// var handleFileSelect = function(evt) {
			// 	var file = evt.currentTarget.files[0];
			// 	if (!/image\/\w+/.test(file.type)) {
			// 		return false;
			// 	}
			// 	var reader = new FileReader();//创建一个文件流
			// 	reader.onload = function(evt) {//创建完成之后执行
			// 		$scope.$apply(function($scope) {
			// 			$scope.myImage = evt.target.result;
             //            console.log($scope.myImage);
			// 		});
			// 	};
			// 	reader.readAsDataURL(file);//把文件流转成base64发给后台
			// };
            //
			// angular.element(document.querySelector('#fileInput')).on('change',handleFileSelect);

			// 初始化页面
			function activate(id) {
				$scope.loading = true;
				$.ajax({
					type : 'PUT',
					dataType : 'json',
					contentType : 'application/json;charset=UTF-8',
					url : 'dac/userManager/detail',
					data : angular.toJson({
						'id' : id
					})
				}).then(function(result) {
					$scope.loading = false;
					if (result.httpCode == 200) {
						$scope.record = result.data;
					} else {
						$scope.msg = result.msg;
					}
					$scope.$apply();
				});
			}


			$scope.openDevice = function() {
				var modalInstance = $modal.open({
					templateUrl : 'mHouseList.html',// script标签中定义的id
					controller : 'mHouseModalCtrl',// modal对应的Controller
					size : 'lg',
					resolve : {
						personType : function() {// 向模态框app中传递参数
							return $scope.record.personType;
						}
					}
				});
				modalInstance.opened.then(function() {// 模态窗口打开之后执行的函数

				});
				modalInstance.result.then(function(result) {
					if(result[0] != "flagController"){//房东
						$scope.record.houseName = result.selected;
						$scope.record.houseIdArray = result.houseIdArray;
						$scope.record.address = result.houseAddress;
					}else{//租客
						$scope.record['houseCode'] = result[1];
						$scope.record['address'] = result[2];
						$scope.record['objectId'] = result[3];
						$scope.record['houseName'] = result[4];
						$scope.record.houseIdArray = null;
					}

				}, function(reason) {
					console.log(reason);

				})
			};

            //警务区的模态框
            $scope.openjwqdm = function() {
                var modalInstance = $modal.open({
                    templateUrl : 'jwq.html',// script标签中定义的id
                    controller : 'jwqModalCtrl',// modal对应的Controller
                    size : 'lg'
                    // resolve : {
                    //     personType : function() {// 向模态框app中传递参数
                    //        return $scope.record.personType;
                    //     }
                    // }
                });
                //选择之后回显到页面上来
                modalInstance.result.then(function(result) {//这里的result是下面的模态回调函数的值
                    $scope.record.policeAreaId = result[1];
                    $scope.record.policeAreaName = result[2];
                },function(reason) {
                    console.log(reason);
                });
            };

			//麦斯读取卡号
			$scope.readCard = function() {
				//var str;
			  	//SynIDCard1.Port = 1001;//document.all['Port'].value
			  	//console.log("端口设置为"+SynIDCard1.Port);
				//var str=SynIDCard1.Init();
				//console.log("初始化结果"+str);
				//console.log(SynIDCard1.ReadCard());
				//$scope.record.personName = SynIDCard1.NameL;
				//$scope.record.sex = SynIDCard1.Sex;
				//$scope.record.nation = SynIDCard1.NationL;
				//$scope.record.birthday = new Date(SynIDCard1.BornL);//SynIDCard1.BornL;
				//$scope.record.censusAddress = SynIDCard1.Address;
				//$scope.record.IDCardNo = SynIDCard1.CardNo;

				document.getElementById("IdCardRead").connectDevice();
                //
				IdCardRead.readCard();
				//console.log("读卡成功"	                       );
				//console.log("姓名:"+IdCardRead.NameA           );
				//console.log("性别:"+IdCardRead.Sex             );
				//console.log("民族:"+IdCardRead.Nation +""+IdCardRead.NationL         );
				//console.log("出生日期:"+IdCardRead.Born        );
				//console.log("地址:"+IdCardRead.Address         );
				//console.log("身份证号:"+IdCardRead.CardNo      );
				//console.log("有效期开始:"+IdCardRead.UserLifeB );
				//console.log("有效期结束:"+IdCardRead.UserLifeE );
				//console.log("发证机关:"+IdCardRead.Police      );
				//console.log("照片文件名:"+IdCardRead.PhotoName );
				//console.log("照片文件名:"+IdCardRead.base64str );
				//$("#headImag").attr("src","data:image/png;base64,"+IdCardRead.base64str)
				
				$.ajax({
					type : 'POST',
					dataType : 'json',
					contentType : 'application/json;charset=UTF-8',
					url : 'dac/userManager/headupload',
					data : angular.toJson({'headPic': IdCardRead.base64str})
				}).then(function(result) {
					$scope.loading = false;
					if (result.httpCode == 200) {
						//$scope.record.authcode = result.hex;
						$("#headImag").attr("src",result.path)
						var photopath = "/dac/userManager/headdownload?fileId="+result.path;
						$scope.record.photoURL = photopath;
						$("#headImag").attr("src",photopath);
					} else {
						//$scope.msg = result.msg;
						toaster.clear('*');
						toaster.pop('error', '', "照片上传失败！");
					}
					$scope.$apply();
				});

				var birthYear = IdCardRead.Born.substring(0,4);
				var birthMonth = IdCardRead.Born.substring(4,6);
				var birthDay = IdCardRead.Born.substring(6,8);

				$scope.record.personName = IdCardRead.NameA.replace(/(^\s*)|(\s*$)/g, "");
				$scope.record.sex = IdCardRead.Sex;
				$scope.record.nation = IdCardRead.Nation;
				$scope.record.birthday = birthYear+"-"+birthMonth+"-"+birthDay;
				$scope.record.censusAddress = IdCardRead.Address.replace(/(^\s*)|(\s*$)/g, "");
				$scope.record.IDCardNo = IdCardRead.CardNo;

			};
			$scope.readIcCard = function (){

				var ports = webSerial.getComPorts();
		        var com = ports;
		        var baudRate = '115200';
		        var result = webSerial.connect(com,baudRate);
		        console.log(result);
		        //var data1 = webSerial.Receive();
		        var webSerial1 = document.getElementById("webSerial");
		        
		        var timer = setInterval(function(){
		    		var data1 = webSerial1.Receive();

		    		if(data1 != null){
		    			console.log(data1);
		    			var code = data1.split(" ");
		    			var targetStr = "";
		    			for(var i = 0;i<code.length;i++){
		    				var tmp = parseInt(code[i],16);
		    				targetStr += String.fromCharCode(tmp);
		    			}
		    			console.log(targetStr);
						$scope.record.authcode = targetStr;
						
		    			webSerial.close();
		    			clearInterval(timer);
		    		}

				},2000);

			}

			
			//判断浏览器是否为IE或edge
			BrowserType();
			function BrowserType(){
				if (!!window.ActiveXObject || "ActiveXObject" in window){
					connect();
				}
			}
			
			//华视电子身份证读卡器连接
			function connect(){
				var CertCtl = document.getElementById("CertCtl");
				try {
					var result = CertCtl.connect();
					getStatus();
			    } catch (e) {
				}
			}
			
			//华视电子身份证读卡器连接状态检测
			function getStatus(){
				var CertCtl = document.getElementById("CertCtl");
				try {
					var result = CertCtl.getStatus();
					var resultObj = eval('('+result+')'); //toJson操作
					console.log(typeof resultObj.status); 	
					resultObj.status ? $scope.cardStatus = "设备未连接" : $scope.cardStatus = "读身份证(仅IE可用)";
				} catch(e) {
				}
			}
		
			//华视电子身份证读卡器读卡
			$scope.readCert = function() {
				var CertCtl = document.getElementById("CertCtl");
				try {
					var result = CertCtl.readCert();
					var resultObj = eval('('+result+')'); //toJson操作
					
					if (resultObj.resultFlag == 0) {
						$scope.checkIDCardNo(resultObj.resultContent); //将读取的卡号进行后台查询
						$scope.record.IDCardNo = resultObj.resultContent.certNumber; //身份证号
						$scope.record.personName = resultObj.resultContent.partyName;//身份证姓名
						$scope.record.censusAddress = resultObj.resultContent.certAddress;//身份证户籍
						
						resultObj.resultContent.gender ? $scope.record.sex = "1" : $scope.record.sex = "2";//身份证性别'
						$scope.record.nation = $("#nation option:contains('" + resultObj.resultContent.nation + "族')").attr('selected', true).val();//身份证民族
						//身份证出生日期
						var bornDay = resultObj.resultContent.bornDay.slice(0,4)+'-'+resultObj.resultContent.bornDay.slice(4,6)+'-'+resultObj.resultContent.bornDay.slice(6,8);
						$("#birthday").val(bornDay);
						//身份证头像
						var imgBase64 = "data:image/jpeg;base64," + resultObj.resultContent.identityPic;
						$("#headImag").prop('src',imgBase64);
					}
					
				} catch(e) {
				}
			}

			//日期控件
	        $scope.dateOptions = {
	             startingDay: 1,
	             class: 'datepicker'
	        };
	        //日期控件
	        $scope.openDatepicker = function($event, i) {
	            $event.preventDefault();
	            $event.stopPropagation();
	            if(i==1){
	    	        $scope.birthday = true;
                }else if(i==2){
	    	        $scope.startTime = true;
                }else if(i==3){
                    $scope.endTime = true;
                }else if(i==4){
                    $scope.liveTime = true;
				}
	        }

	        //手机号码唯一校验
			$scope.checkPhoneNumber = function () {
                var PhoneNumber = $('#mobileNo').val();
                var phoneTest = /^1[3456789]\d{9}$/;
                if(phoneTest.test(PhoneNumber) == true){
                    $.ajax({
                        type : 'POST',
                        dataType : 'json',
                        contentType : 'application/json;charset=UTF-8',
                        url : '/dac/userManager/checkMobile',
                        data : angular.toJson({'mobileNo':PhoneNumber})
                    }).then(function(result) {
                    	console.log(result);
                        $scope.loading = false;
                        if (result.httpCode == 200) {
                            $scope.isuse = false;
                        } else if(result.httpCode== 666){
                            $('#mobileNo').val('')//清空
                            $scope.isuse = true;
                        } else {
                            $scope.msg = result.msg;
                        }
                        $scope.$apply();
                    });
				}else{
					$('#mobileNo').val('')//清空
                    $scope.phoneStyleError = true;
				}

            }
			
	        //身份证唯一校验
			$scope.checkIDCardNo = function (data) {
                var IDCardNo = $('#IDCardNo').val() || data.certNumber;
               	var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
                if(reg.test(IDCardNo)==true){
	                $.ajax({
	                    type : 'POST',
	                    dataType : 'json',
	                    contentType : 'application/json;charset=UTF-8',
	                    url : '/dac/userManager/checkIDCardNo',
	                    data : angular.toJson({'IDCardNo':IDCardNo})
	                }).then(function(result) {
	                	console.log(result);
	                    $scope.loading = false;
	                    if (result.httpCode == 200) {
	                        $scope.IDCardNoHide = false;
	                    } else if(result.httpCode== 666){
	                        $('#IDCardNo').val('')//清空
	                        $scope.IDCardNoHide = true;
	                    } else {
	                        $scope.msg = result.msg;
	                    }
	                    $scope.$apply();
	                });
	                	
                }else{
                	$scope.IDCardNoError = true;
                	$('#IDCardNo').val('')//清空
                }
            }

            //再次获取焦点隐藏提示
            $scope.hideWarn = function () {
                $scope.isuse = false;
                $scope.phoneStyleError = false;
            }
            
            $scope.IDCardNoHideWarn = function () {
                $scope.IDCardNoHide = false;
                $scope.IDCardNoError = false;
            }

            function validate() {
                jQuery('form').validate({
                    rules : {
                        personName : {
                            required : true,
                            stringCheck :[],
                            maxLengthB : [ 20 ]
                        },
                        birthday : {
                            required : true
                        },
                        IDCardNo : {
                            required : true,
                            stringCheck : [],
                            maxLengthB : [ 32 ]
                        },
                        censusAddress : {
                            required : true,
                            stringCheck : [],
                            maxLengthB : [ 200 ]
                        },
                        sex : {
                            required : true
                        },
                        nation : {
                            required : true
                        },
                        personType : {
                            required : true
                        },
                        houseCode : {
                            required : true,
                            stringCheck : [],
                            maxLengthB : [ 20 ]
                        },
//                      nationality : {
//                          required : true,
//                          stringCheck : [],
//                          maxLengthB : [ 20 ]
//                      },
                        mobileNo : {
                            required : true,
                            stringCheck : [],
                            maxLengthB : [ 20 ]
                        },
//                      personState : {
//                          required : true
//                      },
//                      contraceptionState : {
//                          required : true
//                      },
                        address : {
                            required : true,
                            stringCheck : [],
                            maxLengthB : [ 200 ]
                        },
//                      liveTime : {
//                          required : true
//                      },
                        marriageState : {
                            required : true
                        },
                        isWriteOff : {
                            required : true
                        },
                        userName : {
                            required : true,
                            stringCheck : [],
                            maxLengthB : [ 20 ]
                        },
                        nickName : {
                            stringCheck : [],
                            maxLengthB : [ 20 ]
                        },
//						userType : {
//							required : true
//						},
                        userStatus : {
                            required : true
                        },
                        startTime : {
                            required : true
                        },
                        endTime : {
                            required : true
                        },
                        mobileNo2: {
                            required:true,
                        },
//                      jwqdm: {
//                          stringCheck : [],
//                          required:true
//                      },
						studentNo:{
							required:true,
						}
                    },
                    messages : {
                        personName : {
                            required : '请输您的真实姓名',
                            maxLengthB : "姓名不得超过{0}个字符"
                        },
                        birthday : {
                            required : '请选择出生日期'
                        },
                        IDCardNo : {
                            required : '请输入您的身份证号码',
                            maxLengthB : "身份证号码不得超过{0}个字符"
                        },
                        censusAddress : {
                            required : '请输入您的户籍地址',
                            maxLengthB : "户籍地址不得超过{0}个字符"
                        },
                        sex : {
                            required : '请选择您的性别'
                        },
                        nation : {
                            required : '请输入您的民族'
                        },
                        personType : {
                            required : '请选择您的人员类别'
                        },
                        houseCode : {
                            required : '请选择您的房屋名称',
                            maxLengthB : "房屋名称不能为空"
                        },
                        nationality : {
                            required : '请输入您的国籍'
                        },
                        mobileNo : {
                            required : '请输入您的移动电话',
                            maxLengthB : "移动电话不能超过{0}"
                        },
                        personState : {
                            required : '请选择您的人员状态'
                        },
                        contraceptionState : {
                            required : '请选择您的避孕动态'
                        },
                        address : {
                            required : '请输入您的居住地址',
                            maxLengthB : "居住地址不得超过{0}个字符"
                        },
                        liveTime : {
                            required : '请选择您的入住时间'
                        },
                        marriageState : {
                            required : '请选择您的婚姻状况'
                        },
                        isWriteOff : {
                            required : '请确认是否已注销'
                        },
                        userName : {
                            required : '请输入您的用户名称',
                            maxLengthB : "用户名称不得超过{0}个字符"
                        },
                        nickName : {
                            maxLengthB : "用户昵称不得超过{0}个字符"
                        },
//						userType : {
//							required : '请选择用户类型'
//						},
                        userStatus : {
                            required : '请选择您的用户状态'
                        },
                        startTime : {
                            required : '请选择您的开始时间'
                        },
                        endTime : {
                            required : '请选择您的结束时间'
                        },
                        mobileNo2:{
                            required : '请输入您的手机号'
                        },
                        jwqdm: {
                            required:'请选择警务区代码'
                        },
                        studentNo:{
							required:'请输入您的学号',
						}
                    },
                    submitHandler : function() {
                        $scope.submit();
                    }
                });
            };
            
            
    } ]);

      // 表单验证


     app.controller('mHouseModalCtrl', function($scope, $rootScope, $modal,$modalInstance, personType) {

    // 查询条件、参数，用于传递给后台使用
    $scope.param = {};

    // 若为1则显示房东复选框的模态框；若为0则显示租客单选框的模态框。
    $scope.tag = 0;

    $scope.search = function() {
        $scope.loading = true;
        if($scope.pageFlag != 1){//未点击翻页
            $scope.param.pageNum=1;//将页码设置为1，即跳转回第一页
        }else{//点击翻页
            $scope.pageFlag = 2;//将开关值设置为2
        }
        $.ajax({
            type : 'POST',
            dataType : 'json',
            contentType : 'application/json;charset=UTF-8',
            url : '/dac/bm/house/list',
            data : angular.toJson($scope.param)
        }).then(function(result) {
            $scope.loading = false;
            if (result.httpCode == 200) {
                $scope.pageInfo = result;
                console.log(result);
            } else {
                $scope.msg = result.msg;
            }
            $scope.$apply();
        });
    }
    // 调用查询函数
    $scope.search();

    $scope.selectDevice = function(houseCode, address, houseId, houseName) {
        $scope.params = [];
        $scope.params[0] = "flagController";//用于区分租客和房东，有flagController则代表着租客，没有则是房东。
        $scope.params[1] = houseCode;
        $scope.params[2] = address;
        $scope.params[3] = houseId;
        $scope.params[4] = houseName;
        // 这里需要将复选框选中的属性取到，然后交给$modalInstance回显到修改页面
        // 修改页面将复选框传来的值再传给后台
        $modalInstance.close($scope.params);
    };

    // 取消
    $scope.cancel = function() {
        $modalInstance.dismiss('cancel');
    };

    // 翻页
    $scope.pagination = function(page) {
        $scope.param.pageNum = page;
        $scope.pageFlag = 1;//将开关值设置为1
        $scope.search();
    };

    // 定义一个数组，用于接收房东复选框的多值
    $scope.selected = [];
    $scope.houseIdArray = [];
    $scope.houseAddress = [];

    $scope.isChecked = function(houseId) {
        return $scope.selected.indexOf(houseId) >= 0;
    };

    $scope.updateSelection = function($event, item) {
        var checkbox = $event.target;
        var checked = checkbox.checked;
        if (checked) {
            $scope.selected.push(item.houseName+"("+item.houseCode+")");
            $scope.houseIdArray.push(item.houseId);
            $scope.houseAddress.push(item.address);
        } else {
            var idx = $scope.selected.indexOf(item.houseName+"("+item.houseCode+")");
            $scope.selected.splice(idx, 1);

            var houseIdx = $scope.houseIdArray.indexOf(item.houseId);
            $scope.houseIdArray.splice(houseIdx, 1);

            var addressIdx = $scope.houseAddress.indexOf(item.address);
            $scope.houseAddress.splice(addressIdx, 1);
        }
    };

    $scope.saveHouse = function() {
        $scope.records = {};
        $scope.records.selected = $scope.selected;
        $scope.records.houseIdArray = $scope.houseIdArray;
        $scope.records.houseAddress = $scope.houseAddress;
        $modalInstance.close($scope.records);
    }

});

     app.controller('jwqModalCtrl', function($scope, $rootScope, $modal,$modalInstance) {

    // 查询条件、参数，用于传递给后台使用
    $scope.param = {};
    // 若为1则显示房东复选框的模态框；若为0则显示租客单选框的模态框。
    $scope.tag = 0;

    $scope.search = function() {
        $scope.loading = true;
        if($scope.pageFlag != 1){//未点击翻页
            $scope.param.pageNum=1;//将页码设置为1，即跳转回第一页
        }else{//点击翻页
            $scope.pageFlag = 2;//将开关值设置为2
        }
        $.ajax({
            type : 'POST',
            dataType : 'json',
            contentType : 'application/json;charset=UTF-8',
            url : 'dac/userManager/jwqdm/list',
            data : angular.toJson($scope.param)
        }).then(function(result) {
            $scope.loading = false;
            if (result.httpCode == 200) {
                $scope.pageInfo = result;
                //console.log(result);
            } else {
                $scope.msg = result.msg;
            }
            $scope.$apply();
        });
    }

    // 调用查询函数
    $scope.search();

    $scope.selectjwq = function(jwqdm,jwqmc) {
        $scope.params = [];
        $scope.params[1] = jwqdm;
        $scope.params[2] = jwqmc;
        // 这里需要将复选框选中的属性取到，然后交给$modalInstance回显到修改页面
        // 修改页面将复选框传来的值再传给后台
        $modalInstance.close($scope.params);
    };

    // 取消
    $scope.cancel = function() {
        $modalInstance.dismiss('cancel');
    };

    // 翻页
    $scope.pagination = function(page) {
        $scope.param.pageNum = page;
        $scope.pageFlag = 1;//将开关值设置为1
        $scope.search();
    };


});